import { useCallback } from 'react';
import useFetch from 'use-http';
import stringify from 'qs-stringify';

/**
 * 获取保险产品列表
 */
export const useProducts = () => {
  const { loading, data = [] } = useFetch('/api/products', {}, []);
  return [loading, data];
};

/**
 * 获取产品详情，并在这个页面进行页面录制
 *
 * @param {string} sid
 */
export const useProduct = (sid) => {
  const { loading, data = {} } = useFetch(`/api/products/${sid}`, {}, [sid]);
  return [loading, data];
};

/**
 * 获取回放列表
 */
export const useTracks = () => {
  const { loading, data = [] } = useFetch('/api/tracks', {}, []);
  return [loading, data];
};

/**
 * 获取回放数据，回放数据由多个片段组成，并在一个界面进行显示
 *
 * @param {string} id 回放数据的唯一标识符
 */
export const useReplay = (id) => {
  const { loading, data = {} } = useFetch(`/api/replay/${id}`, {}, [id]);
  return [loading, data];
};

/**
 * 将前端记录的数据发送保存至服务器端
 * 发送的同时记录下当前页面的大小，用于支持后续回放
 */
export const useTracking = (session) => {
  const { loading, data = {}, post } = useFetch(`/api/tracks/${session}`);

  const trackEvent = useCallback(
    async (data, done = false) => {
      const params = {
        height: window.innerHeight,
        width: window.innerWidth,
        done
      };
      return await post(`?${stringify(params)}`, data);
    },
    [post]
  );
  return [loading, data, trackEvent];
};

export const useUpload = (session) => {
  const { loading, post } = useFetch(`/api/replay/${session}`);

  const upload = useCallback(
    async (blob) => {
      const form = new FormData();
      form.append('file', blob);
      await post(form);
    },
    [post]
  );
  return [loading, upload];
};
